# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from .models import SipPro
import os
import xadmin
from .MyIO import *
from .ConnFreeswitch import *
from django import forms
from .MySqlite import *
from django.http import Http404, HttpResponseRedirect

UPLOAD_PATH_FILE = "/usr/local/freeswitch/sounds/zh/cn/callie/ivr/8000/"
config_file_patch = "/usr/local/freeswitch/conf/"
getcwd="/var/www/MyIPPbx"
class ivrAdmin(object):
    list_display = ['name', 'dn','extension', 'transfer_0']
    list_per_page = 10
    add_form_template = 'myform.html'
    change_form_template = 'myform.html'
    xadmin.views.edit.UpdateAdminView.exclude = ['name']

    def save_models(self):
        obj = self.new_obj
        #obj.greet_long = "Me_" + obj.name + ".wav"
        #obj.greet_short = "Me_" + obj.name + "_short.wav"
        self.new_obj.save()
        CopyFile(os.getcwd()+ "/" + str(obj.greet_long), UPLOAD_PATH_FILE + "Me_" + obj.name + ".wav")
        CopyFile(os.getcwd() + "/" + str(obj.greet_long), UPLOAD_PATH_FILE + "Me_" + obj.name + "_short.wav")
        #DeleteFile(os.getcwd() + "/" + str(obj.greet_long))
        #DeleteFile(os.getcwd() + "/" + str(obj.greet_short))
        greet_long = "ivr/Me_" + obj.name + ".wav"
        greet_short = "ivr/Me_" + obj.name + "_short.wav"
        if str(obj.invalid_sound) !="":
            invalid_sound = "ivr/Me_" + obj.name + "_invalid.wav"
            CopyFile(os.getcwd() + "/" + str(obj.invalid_sound), UPLOAD_PATH_FILE + "Me_" + obj.name + "_invalid.wav")
            #DeleteFile(os.getcwd() + "/" + invalid_sound)
        else:
            invalid_sound = "ivr/ivr-that_was_an_invalid_entry.wav"
        if str(obj.exit_sound) !="":
            exit_sound = "ivr/Me_" + obj.name + "_exit.wav"
            CopyFile(getcwd + "/" + str(obj.exit_sound), UPLOAD_PATH_FILE + "Me_" + obj.name + "_exit.wav")
            #DeleteFile(os.getcwd() + "/" + exit_sound)
        else:
            exit_sound = "voicemail/vm-goodbye.wav"

        info = ReadFile(os.path.join(getcwd+"/pbx/tpl",'myivr_demo.xml'))
        info = info.replace('{name}', obj.name)
        info = info.replace('{greet-long}', greet_long)
        info = info.replace('{greet-short}', greet_short)
        info = info.replace('{invalid-sound}', invalid_sound)
        info = info.replace('{exit-sound}', exit_sound)
        info = info.replace('{timeout}', str(obj.timeout))
        info = info.replace('{max-failures}', str(obj.max_failures))
        info = info.replace('{max-timeouts}', str(obj.max_timeouts))
        info = info.replace('{inter-digit-timeout}', str(obj.inter_digit_timeout))
        info = info.replace('{digit-len}', str(obj.digit_len))
        info = info.replace('{menu-exec-app}', obj.extension)
        if str(obj.transfer_0) != "None":
            info = info.replace('<!-- 0 -->', '<entry action="menu-exec-app"   digits="0" param="transfer '+str(obj.transfer_0)+' XML default"/>')
        if str(obj.transfer_1) != "None":
            info = info.replace('<!-- 1 -->', '<entry action="menu-exec-app"   digits="1" param="transfer '+str(obj.transfer_1)+' XML default"/>')
        if str(obj.transfer_2) != "None":
            info = info.replace('<!-- 2 -->', '<entry action="menu-exec-app"   digits="2" param="transfer '+str(obj.transfer_2)+' XML default"/>')
        if str(obj.transfer_3) != "None":
            info = info.replace('<!-- 3 -->', '<entry action="menu-exec-app"   digits="3" param="transfer '+str(obj.transfer_3)+' XML default"/>')
        if str(obj.transfer_4) != "None":
            info = info.replace('<!-- 4 -->', '<entry action="menu-exec-app"   digits="4" param="transfer '+str(obj.transfer_4)+' XML default"/>')
        if str(obj.transfer_5) != "None":
            info = info.replace('<!-- 5 -->', '<entry action="menu-exec-app"   digits="5" param="transfer '+str(obj.transfer_5)+' XML default"/>')
        if str(obj.transfer_6) != "None":
            info = info.replace('<!-- 6 -->', '<entry action="menu-exec-app"   digits="6" param="transfer '+str(obj.transfer_6)+' XML default"/>')
        if str(obj.transfer_7) != "None":
            info = info.replace('<!-- 7 -->', '<entry action="menu-exec-app"   digits="7" param="transfer '+str(obj.transfer_7)+' XML default"/>')
        if str(obj.transfer_8) != "None":
            info = info.replace('<!-- 8 -->', '<entry action="menu-exec-app"   digits="8" param="transfer '+str(obj.transfer_8)+' XML default"/>')
        if str(obj.transfer_9) != "None":
            info = info.replace('<!-- 9 -->', '<entry action="menu-exec-app"   digits="9" param="transfer '+str(obj.transfer_9)+' XML default"/>')
        WriteFile(config_file_patch + "ivr_menus/"+obj.name+".xml", info)
        dinfo = ReadFile(os.path.join(getcwd + "/pbx/tpl", 'sampleIVR.xml'))
        dinfo = dinfo.replace('{name}', obj.name)
        dinfo = dinfo.replace('{destination_number}', str(obj.dn))
        dialplan = ReadFile(config_file_patch + "dialplan/default.xml")
        urllist = str(self.request.get_full_path()).split('/')
        if len(urllist) == 5:
            dialplan = dialplan.replace("<!-- a sample IVR  -->","<!-- a sample IVR  -->\r\n"+dinfo)
        else:
            myivr =  ReadFile(os.path.join(getcwd + "/pbx/tpl", 'ivr_' + obj.name + '.xml'))
            dialplan = dialplan.replace(myivr,dinfo)
            getFileList(os.getcwd() + "/upload/")
        WriteFile(config_file_patch + "dialplan/default.xml", dialplan)
        WriteFile(os.path.join(getcwd + "/pbx/tpl", 'ivr_' + obj.name + '.xml'), dinfo)
        r = ReloadXml()
        if r == -1:
            self.message_user(u'告警,IPPBX加载失败，请重启IPPBX或者手动加载!', 'warning')

    def delete_models(self, obj):
        try:
            deleteFile(obj, config_file_patch + "ivr_menus/", ".xml")
            deleteFileIvr("Me_", obj, UPLOAD_PATH_FILE, ".wav")
            deleteFileIvr("Me_", obj, UPLOAD_PATH_FILE, "_short.wav")
            deleteFileIvr("Me_", obj, UPLOAD_PATH_FILE, "_invalid.wav")
            deleteFileIvr("Me_", obj, UPLOAD_PATH_FILE, "_exit.wav")
            dialplan = ReadFile(config_file_patch + "dialplan/default.xml")
            for vars in obj:
                dinfo = ReadFile(os.path.join(getcwd + "/pbx/tpl", 'ivr_' + str(vars) + '.xml'))
                dialplan = dialplan.replace("\r\n" + dinfo, "")
                WriteFile(config_file_patch + "dialplan/default.xml", dialplan)
            deleteFileIvr("ivr_", obj, getcwd + "/pbx/tpl/", ".xml")
            r = ReloadXml()
            if r == -1:
                self.message_user(u'告警,IPPBX加载失败，请重启IPPBX或者手动加载!', 'warning')
            obj.delete()
        except Exception as e:
            obj.delete()
            print str(e)
        getFileList(os.getcwd()+"/upload/")

def getFileList(path):
    file_name = os.listdir(path)
    for file in file_name:
        strsql = "select * from pbx_ivr where greet_long = 'upload/"+file+"' or greet_short = 'upload/"+file+"' or invalid_sound = 'upload/"+file+"' or exit_sound= 'upload/"+file+"'"
        #print(strsql)
        l = len(ReadSql(strsql))
        if l == 0:
            DeleteFile(path+file)


